﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Orange.Mvc4App.Models;

namespace Orange.Mvc4App.Services {

    public interface IGroupService : IBaseService<Group> {
        List<Customer> GetMember(string groupid);
        List<Customer> GetNoMember(string groupid);
        void AddMemeber(CustomerGroup member);
        void RemoveMemeber(CustomerGroup member);
    }

    public class GroupService : BaseService, IGroupService {
        public IList<Group> GetList(Func<Group, bool> filters) {
            if (filters != null)
                return db.Groups.Where(filters).ToList();
            else
                return db.Groups.ToList();
        }

        public Group Find(params object[] keys) {
            return db.Groups.Find(keys);
        }

        public void Add(Group model) {
            db.Groups.Add(model);
        }

        public void Update(Group model) {
            db.Entry(model).State = EntityState.Modified;
        }

        public void Delete(Group model) {
            db.Groups.Remove(model);
        }

        public void Save() {
            db.SaveChanges();
        }

        public void Dispose() {
            db.Dispose();
        }

        public List<Customer> GetMember(string groupid) {
            return db.Customers.Where(c => db.CustomerGroups
                .Where(r => r.Groupid == groupid)
                .Select(cg => cg.Customerid).Contains(c.CustomerId))
                .ToList();
        }

        public List<Customer> GetNoMember(string groupid) {
            return db.Customers.Where(c => !db.CustomerGroups
                .Where(r => r.Groupid == groupid)
                .Select(cg => cg.Customerid).Contains(c.CustomerId))
                .ToList();
        }

        public void AddMemeber(CustomerGroup member) {
            db.CustomerGroups.Add(member);
        }


        public void RemoveMemeber(CustomerGroup member) {
            db.CustomerGroups.Remove(member);
        }
    }
}